<template>
    <!-- 聊天  已读 删除 数据展示还有点问题-->
    <!-- {{ props }} -->
    <div v-if="toUserInfo" class="big-box">
        <div class="lt-top">
            <!-- {{ toUserInfo }} -->
            <span>{{ toUserInfo.nickName }}</span>
            <span>最近消息时间：{{ lastUpdataTime }}</span>

        </div>
        <div class="lt" ref="containerRef">
            <div v-for="(msg, index) in messageQueue" :key="index">
                <div v-if="msg.self" class="msg-right">
                    <!-- 消息框 -->
                    <div class="nr-right">{{ msg.content }}</div>
                    <!-- 头像 -->
                    <img :src="msg.senderProfilePhoto" class="tx-img">
                </div>

                <div v-else class="msg-left">
                    <img :src="msg.profilePhoto" class="tx-img">
                    <div class="nr-left">{{ msg.content }}</div>
                </div>
            </div>
        </div>
        <!-- 输入 按钮 -->
        <div class="sr">
            <!-- {{ toUserInfo }} -->
            <n-input v-model:value="text" type="textarea" class="srk"></n-input>
            <div style="display: flex;justify-content: flex-end;">
                <n-button @click="sendMsg()" type="primary" style="margin: 10px 10px 0px 0px">发送</n-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { computed, nextTick, onMounted, onUpdated, ref, toRef, watch } from 'vue';
import useUserStore from '@/stores/useUserStore';
import userHttp from '@/api/userHttp';
import timeUtils from '@/utils/timeUtils';
const userStore = useUserStore()
//发件人是自己就是true 存放页面数据
const messageQueue = ref([])
//获取页面容器节点
const containerRef = ref(null);
const props = defineProps(['idData'])
const emit = defineEmits(['click-event'])

//父组件传过来的接收双方id 对象
const idData = props.idData
//获取到的接收用户数据
const toUserInfo = ref(null)
//输入框数据
const text = ref("")
//连接
let ws = new WebSocket(`ws://localhost:8085/myWs/${userStore.userInfo.userId}`)
onMounted(() => {
    scrollToBottom();
})



const lastUpdataTime = computed(() => {
    //console.log("长度", messageQueue.value.length);
    if (messageQueue.value.length > 0) {
        const [lastObject] = messageQueue.value.slice(-1);
        //如果存在时间
        if (lastObject.sendTime != null) {
            //时间去T
            return lastObject.sendTime.replace("T", " ")
        }
    } else {
        return null
    }

})

//获取收件人的数据
const getTouserData = (toUserId) => {
    //如果是老师的聊天就获取该学生的数据 等下在写个如果是学生界面的获取数据
    //这个if可以删除 主要是老师删除会话后 toUserId 为空 这里会报错
    if (toUserId != null) {
        userHttp.getUserInfo(toUserId).then((res) => {
            toUserInfo.value = res.data
            //console.log("获取消息接收人数据", toUserInfo.value);
        }).then(() => {
            getChatHistory()
        })
    }

}

//获取用户 和收件人的聊天记录 根据用户id 和收件人Id
const getChatHistory = () => {
    userHttp.getChatHistory(userStore.userInfo.userId, idData.toUserId).then((res) => {
        //console.log("获取聊天记录", res);
        res.data.forEach(element => {
            insertData(element.message, element.self, element.createTime)
        });
    })
}

//将要聊天记录数据插入页面
const insertData = (content, self, sendTime) => {
    messageQueue.value.push({
        content: content,
        sendTime: sendTime ? sendTime : null,//发送时间  
        self: self,
        //自己
        senderId: userStore.userInfo.userId,
        senderName: userStore.userInfo.nickName,
        senderProfilePhoto: userStore.userInfo.profilePic,
        //对面
        username: toUserInfo.value.nickName,
        addresseeId: idData.toUserId,
        profilePhoto: toUserInfo.value.profilePic,
    });
    nextTick(() => { // 确保 DOM 更新完成后执行滚动操作
        scrollToBottom();
    });
}

//监听id 变化调用方法 当聊天对象改变时触发
watch(() => props.idData.toUserId, (newValue, oldValue) => {
    //改变 toUserId
    idData.toUserId = newValue
    //清空聊天框
    messageQueue.value = []
    //根据toUSer的Id 获取toUser的数据
    getTouserData(newValue)

});

//发送信息
const sendMsg = () => {
    //获取当前时间
    const currentTime = timeUtils.currentTime()
    //console.log({currentTime});
    //加入到消息列表
    insertData(text.value, true, currentTime)
    //发送消息
    ws.send(idData.toUserId + ":" + text.value)
    //清空输入框
    text.value = ""
    if (userStore.userInfo.role == '教师') {
        //改变信息状态 重新获取学生列表
        emit('click-event');
    }
}

//设置 WebSocket连接打开时的 执行的回调函数
ws.onopen = () => {
    // ws.send("你好")
}

//监听收到的消息
ws.onmessage = (event) => {

    //双方都在线但是 一开始没有 老师方老师方没有列表 收到消息后 写写这个 有点问题
    if (userStore.userInfo.role == '教师' && toUserInfo.value== null) {
        //改变信息状态 重新获取学生列表
        emit('click-event');
    }

    console.log("监听收到的消息", { event });
    //消息内容
    const receivedMessage = event.data;
    //获取当前消息
    const currentTime = timeUtils.currentTime()
    //收到的消息肯定不是自己发的 所以用 false
    insertData(receivedMessage, false, currentTime)
    //console.log("打印消息列表", messageQueue.value);
    if (userStore.userInfo.role == '教师') {
        //改变信息状态 重新获取学生列表
        emit('click-event');
    }
};

// 滚动到容器底部
const scrollToBottom = () => {
    if (containerRef.value) {
        containerRef.value.scrollTo({
            top: containerRef.value.scrollHeight,
            behavior: 'smooth'
        });
    }
};

</script>

<style scoped>
.big-box {}

/* 聊天框 */
.lt {
    height: 600px;
    overflow: auto;
    border-top: 2px rgb(0, 0, 0, 0.2) dotted;
    border-bottom: 2px rgb(0, 0, 0, 0.2) dotted;
    flex: 8;
    border-radius: 10px;
    background-color: rgba(251, 249, 242, 0.2);
}

.sr {
    flex: 2;
    margin-top: 10px;
    border-radius: 10px;
    padding: 10px;
    border-top: 2px rgb(0, 0, 0, 0.2) dotted;
    border-bottom: 2px rgb(0, 0, 0, 0.2) dotted;
    background-color: rgba(255, 255, 255, 0.1);
}

.lt-top {
    padding: 5px;
    height: 40px;
    margin-bottom: 5px;
    border: 1px rgb(216, 202, 230) solid;
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    align-content: center;
    justify-content: center;
}

.lt-top :nth-child(1) {
    display: flex;
    justify-content: center;
}

.lt-top :nth-child(2) {
    font-size: 10px;
    display: flex;
    justify-content: flex-end;
}

.msg-left {
    margin-top: 10px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    padding: 5px;

}

.tx-img {
    width: 50px;
    border-radius: 50px;
    cursor: pointer;
}



.msg-right {
    margin-top: 10px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 5px;

}


/* 对方发的信息 */
.nr-left {
    margin-left: 10px;
    border-radius: 10px;
    padding: 10px;
    max-width: 500px;
    justify-content: flex-start;
    border: 1px rgb(0, 0, 0, 0.2) solid;
    overflow-wrap: break-word;
    font-family: '华文黑体';
}

/* 我发的信息 */
.nr-right {
    margin-right: 10px;
    border-radius: 10px;
    padding: 10px;
    max-width: 500px;
    justify-content: flex-start;
    background-color: rgb(188, 232, 232, 0.2);
    overflow-wrap: break-word;
    font-family: '华文黑体';
}

.srk {
    height: 120px;
    border-radius: 10px;
}
</style>